import logging
import cgi
import os
import datetime

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from droidguide_classes import *

def createDeviceOnSite(deviceName, connectivity):
    location = Location(lat=0.0, long=0.0, speed=0.0, datetime=datetime.datetime.now(), latlong = db.GeoPt(0.0,0.0))
    location.put()
    device = Device()
    device.location_key = str(location.key())
    device.name = deviceName
    device.batteryLevel = 100.0
    device.connectivity = connectivity
    device.put()
    return device

def createDroidGuideUser(device, user):
    droidGuideUser = DroidGuideUser()
    droidGuideUser.user = user
    droidGuideUser.device_key = str(device.key())
    droidGuideUser.state = 'ACTIVE'
    droidGuideUser.login_time = datetime.datetime.now()              
    droidGuideUser.put()
    return droidGuideUser

def executeLogin(self):
      email = self.request.get('email')
      deviceKey = self.request.get('device_key')
      deviceName = self.request.get('device_name')
      connectivity = self.request.get('connectivity')
      nickname = self.request.get('nickname')
      device = None
      checkRequiredParams(self, ['email', 'device_name'])
      if not deviceName:
          logging.info('device name not found: %s' % deviceName)
	  addMessage('device name not found', self)
      else:
          q = Device.gql("WHERE name = :1 ", deviceName)
          device = q.get()
          if not device:
              logging.info('no device found')
    	      device = createDeviceOnSite(deviceName, connectivity)
          else:
    	      logging.info('device found: %s' % str(device.key()))
	      device.connectivity = connectivity
	      device.put()
          deviceKey = str(device.key())
          logging.info('device key %s' % deviceKey)
          
          if email:
              user = users.User(email)          
              q = db.GqlQuery("SELECT * FROM DroidGuideUser WHERE user = :1", user)
              droidGuideUser = q.get()
              # if the droid guide user doesnt exist
              if not droidGuideUser:
                  droidGuideUser = createDroidGuideUser(device, user)
              elif droidGuideUser.device_key != str(device.key):
                  droidGuideUser.device_key = str(device.key)
	          droidGuideUser.put()
              droidGuideUser.logout_time = None
              droidGuideUser.put()

	      logging.info('user logged in %s' % str(droidGuideUser.key()))

              printObjectShort(self, droidGuideUser)
              printObjectShort(self, device)
              printObjectShort(self, getObject(device.location_key))
        
def executeLogout(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)

      if droidGuideUser_key:
          droidGuideUser = getObject(droidGuideUser_key);
          if droidGuideUser:
              droidGuideUser.state = 'INACTIVE'
              droidGuideUser.logout_time = datetime.datetime.now()
              droidGuideUser.put()
              addMessage('logout successful', self)
          else:
              addMessage('droid guide user not found', self)

def deleteObject(self):
    droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
    device_key = deviceKey = self.request.get('device_key')
    if droidGuideUser_key:
        droidGuideUser = getObject(droidGuideUser_key)
        if droidGuideUser:
            droidGuideUser.delete() 
            addMessage('droid guide user deleted successfully', self)
    elif device_key:
        device = getObject(device_key)
        if device:
            device.delete()
            addMessage('device deleted successfully', self)        

class Process(webapp.RequestHandler):
  def get(self):
      
      operation = self.request.get('operation')

      startDroidGuideMessage(self)

      # login task
      #http://localhost:8080/user/process?operation=login&email=<String>&deviceName=<String>&connectivity=<String>
      if operation == 'login':
          executeLogin(self)

      # logout task
      #http://localhost:8080/user/process?operation=logout&droidGuideUser_key=<String>
      elif operation == 'logout':
          executeLogout(self)

      # list all events
      #http://localhost:8080/user/process?operation=list
      elif operation == 'list':
          listObjects(DroidGuideUser, self)
          listObjects(Device, self)
    
      elif operation == 'delete':
          deleteObject(self)

      elif operation == 'deleteall':
          deleteAll(DroidGuideUser)
          deleteAll(Device)
          addMessage('objects deleted successfully', self)

      finishDroidGuideMessage(self)

application = webapp.WSGIApplication([('/user/process', Process)], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
